<template>
  <main-card-admin :title="title" :loading="studentLoading || recordLoading" :crumbs="crumbs" :show-screen-space="false">
    <template #tool-btn v-if="detailData">
      <a-button class="download-attachment" @click="downloadALLFile"
        ><img src="@/assets/img/admin/learning-case/download-2-line.svg" alt="" />下载全部附件</a-button
      >
    </template>
    <template #default>
      <div class="main-wrap flex">
        <div class="result-wrap">
          <a-input v-model:value="pageForm.name" v-trim class="mb-20" placeholder="学生姓名、学号" @keyup.enter="getStudentsList">
            <template #prefix> <i class="iconfont icon-search-line"></i> </template>
          </a-input>
          <a-select v-model:value="pageForm.learnTaskStudentStatus" class="w-100% mb-20" :options="options" @change="getStudentsList" />

          <!-- 学生列表 -->
          <div class="students-list my-scrollbar">
            <div
              v-for="(item, index) in studentsList"
              :key="index"
              class="student-item flex"
              :class="current === index ? 'bg' : ''"
              @click="changeResultShow(item, index)"
            >
              <div class="info" :title="`${item.username}（${item.number}）`">{{ item.username }}（{{ item.number }}）</div>
              <div class="status" :style="{ color: getStatusColor(item.learningStatus) }">{{ getStatusLabel(item.learningStatus) }}</div>
            </div>
          </div>
        </div>
        <div class="border">
          <div class="showing-wrap my-scrollbar">
            <!-- <a-spin :spinning="spinning" class="spin-wrap"> -->
            <gptChatRecords v-if="type === '0'" :message-records="result.messageRecords ? result.messageRecords : []" :name="currentName" />
            <gptDrawRecords v-else-if="type !== '0'" :draw-records="result.drawRecords ? result.drawRecords : []" />
            <!-- </a-spin> -->
          </div>
          <div class="save-wrap">
            <div class="form-item">
              <div class="title">附件</div>
              <div class="file flex">
                <div class="info flex">
                  <img src="@/assets/img/admin/learning-case/folder-3-line.svg" />
                  <div>
                    <div class="name">{{ result.attachmentName || '暂无' }}</div>
                    <div class="size">{{ sizeFilter(result.attachmentSize || 0) }}</div>
                  </div>
                </div>
                <div class="btn">
                  <img class="mr-12" style="cursor: pointer" src="@/assets/img/admin/learning-case/eye-line.svg" @click="review" />

                  <img
                    style="cursor: pointer"
                    src="@/assets/img/admin/learning-case/download-2-line-gray.svg"
                    @click="downloadStudentFile"
                  />
                </div>
              </div>
            </div>
            <div class="form-item">
              <div class="title">评价分数</div>
              <a-form ref="formRef" :rules="rules" :model="formState">
                <a-form-item label="" name="scoreVal">
                  <a-input v-model:value="formState.scoreVal" placeholder="请输入评价分数，满分100" />
                </a-form-item>
              </a-form>
            </div>
            <a-button type="primary" class="w-100% mt-4" @click="saveScore">保存评价</a-button>
          </div>
        </div>
      </div>
    </template>
  </main-card-admin>
</template>
<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { sizeFilter } from 'g6-fn'
  import { computed, onMounted, reactive, ref } from 'vue'
  import { useRoute } from 'vue-router'

  import { fetchDownload, learningTasksManageApi } from '@/services/api'
  import { waitLoading } from '@/utils'

  import gptChatRecords from '../components/gpt-chat-records/index.vue'
  import gptDrawRecords from '../components/gpt-draw-records/index.vue'
  import { DetailData } from '../types/index'
  import { getStatusColor, getStatusLabel } from '../utils'

  const route = useRoute()
  const { id, name, type, orgId } = route.query as any
  console.log('id========', id, name, type, orgId)

  // 获取详情数据
  const detailData = ref<DetailData>({
    infoDTOList: [],
    attachment: '',
    score: null
  })
  const studentLoading = ref<boolean>(false)
  const recordLoading = ref<boolean>(false)

  // 面包屑
  const crumbs = computed(() => {
    return [
      { path: `/admin/learning-tasks-manage/${type === '0' ? 'dialog' : 'draw'}-list`, name: `${type === '0' ? '对话' : '绘图'}任务` },
      { name: `${type === '0' ? '对话' : '绘图'}评价（${name || ''}）` }
    ]
  })
  const title = computed(() => {
    return `${type === '0' ? '对话' : '绘图'}评价（${name || ''}）`
  })

  const pageForm = ref<Record<string, number | string>>({
    name: '',
    learnTaskStudentStatus: '',
    orgId: orgId,
    learnTaskId: id
  })
  const options = ref<Record<string, number | string>[]>([
    {
      value: '',
      label: '全部状态'
    },
    {
      value: 0,
      label: '未提交'
    },
    {
      value: 1,
      label: '未评价'
    },
    {
      value: 2,
      label: '已评价'
    }
  ])

  const formState = reactive({
    scoreVal: ''
  })
  const formRef = ref()

  const rules: Record<string, Rule[]> = {
    scoreVal: [
      {
        pattern: /^\d+$/,
        message: '仅支持数字'
      },
      {
        required: true,
        message: '请输入评价分数'
      }
    ]
  }

  const attachment = ref<string>('')
  // 学生评价列表
  const studentsList = ref<Record<string, string | number>[]>([])

  const getStudentsList = async (): Promise<void> => {
    studentLoading.value = true
    const { data } = await learningTasksManageApi.evaluationStudentsList({ ...pageForm.value })
    studentsList.value = data.students || []
    attachment.value = data.attachment

    if (studentsList.value.length > 0) {
      currentStudentId.value = studentsList.value[0].id
      // 获取右侧数据
      const param = {
        permissionUserId: currentStudentId.value,
        learnTaskId: id
      }
      getSingleStudentEvaluation(param)
    }
    studentLoading.value = false
  }
  // 点击切换
  const current = ref<number>(0)
  // 当前选中学生姓名
  const currentName = ref<string>('')
  // 当前选中学生id
  const currentStudentId = ref<string | number>('')
  const changeResultShow = (item: any, index: number) => {
    current.value = index
    currentStudentId.value = item.id
    const params = {
      permissionUserId: currentStudentId.value,
      learnTaskId: id
    }
    currentName.value = item.username
    getSingleStudentEvaluation(params)
    scoreVal.value = ''
  }
  // 记录
  const result = ref<Record<string, any>>({
    messageRecords: [],
    drawRecords: [],
    attachmentName: '',
    attachmentSize: null,
    attachmentUrl: null
  })

  // 获取详细数据
  const getSingleStudentEvaluation = async (params: any): Promise<void> => {
    recordLoading.value = true
    const { data } = await learningTasksManageApi.singleStudentEvaluation(params)

    if (data) {
      console.log('获取详细数据:', data)
      result.value.attachmentName = extractValueBetweenPercentAndPdf(data.attachment) || ''
      if (type === '0') {
        result.value.messageRecords = data.infoDTOList
      } else {
        result.value.drawRecords = data.generateRecordEvaluateVOList
      }
      formState.scoreVal = data.score

      result.value.attachmentUrl = data.attachment
      result.value.attachmentSize = Number(data.size)
    } else {
      result.value = {}
      formState.scoreVal = ''
    }
    // result.value.messageRecords = [
    //   {
    //     time: '2024年6月20日 12:18',
    //     words: [
    //       'Silhouette Art',
    //       'breathtaking ( absurdres divine aesthetic  FaeTastic extravaganza alcohol ink sketch). amazing',
    //       'fine',
    //       'detailed',
    //       'masterpiece',
    //       'lovely',
    //       'charming',
    //       'awe-inspiring',
    //       'radiant',
    //       'magnificent. (all dark hues and fine vibrant orange glowing smoldering accent and shiny gold color scheme:1.02). glossy. <lora:InkArtXL_1.2:0.4> <lora:FaeTastic:0.35> . award-winning',
    //       'professional',
    //       'highly detailed . extremely high-resolution details',
    //       'photographic',
    //       'realism pushed to extreme',
    //       'fine texture',
    //       'incredibly lifelike',
    //       'high contrast',
    //       'well defined'
    //     ],
    //     pic: [
    //       '/src/assets/img/rotation-img.png',
    //       '/src/assets/img/rotation-img.png',
    //       '/src/assets/img/rotation-img.png',
    //       '/src/assets/img/rotation-img.png',
    //       '/src/assets/img/rotation-img.png'
    //     ]
    //   },
    //   {
    //     time: '2024年6月20日 12:18',
    //     words: [
    //       'Silhouette Art',
    //       'breathtaking ( absurdres divine aesthetic  FaeTastic extravaganza alcohol ink sketch). amazing',
    //       'fine',
    //       'detailed',
    //       'masterpiece',
    //       'lovely'
    //     ],
    //     pic: [
    //       '/src/assets/img/rotation-img.png',
    //       '/src/assets/img/rotation-img.png',
    //       '/src/assets/img/rotation-img.png',
    //       '/src/assets/img/rotation-img.png',
    //       '/src/assets/img/rotation-img.png',
    //       '/src/assets/img/rotation-img.png',
    //       '/src/assets/img/rotation-img.png',
    //       '/src/assets/img/rotation-img.png',
    //       '/src/assets/img/rotation-img.png',
    //       '/src/assets/img/rotation-img.png'
    //     ]
    //   }
    // ]
    recordLoading.value = false
  }

  // 解析文件名
  const extractValueBetweenPercentAndPdf = (url: string): string => {
    // console.log('解析文件名:', url)
    if (url) {
      // 查找 % 的位置
      const percentIndex = url.indexOf('%')
      // 查找 .pdf 的位置
      const pdfIndex = url.indexOf('.pdf', percentIndex)
      const zipIndex = url.indexOf('.zip', percentIndex)

      // 如果找到这两个位置
      if (percentIndex !== -1 && pdfIndex !== -1) {
        // 提取 % 到 .pdf 之间的字符串

        return decodeURIComponent('%' + url.substring(percentIndex + 1, pdfIndex)) + '.pdf'
      }

      // 如果找到这两个位置
      if (percentIndex !== -1 && zipIndex !== -1) {
        // 提取 % 到 .zip 之间的字符串

        return decodeURIComponent('%' + url.substring(percentIndex + 1, zipIndex)) + '.zip'
      }

      // 如果没有找到 % 或 .pdf，则返回 ''
      return ''
    }
    return ''
  }

  // 预览
  const review = () => {
    if (result.value.attachmentUrl) {
      window.open(result.value.attachmentUrl)
    }
  }
  // 下载
  const downloadStudentFile = () => {
    if (result.value.attachmentUrl === '') {
      message.error('当前不存在可下载的附件')
    } else {
      waitLoading(fetchDownload(result.value.attachmentUrl, result.value.attachmentName), {
        loadingText: '附件下载中...请稍后',
        errorText: '文件下载失败',
        successText: '文件下载成功'
      })
    }
  }

  // 评价
  const scoreVal = ref<string>('')

  // 下载全部文件
  const downloadALLFile = async (): Promise<void> => {
    console.log('-=------')

    // const permissionUserIds = studentsList.value.map((student: any) => {
    //   return student.id
    // })
    message.loading('附件下载中...请稍后')
    const { data } = await learningTasksManageApi.evaluationDownload(
      {
        learnTaskId: id,
        permissionOrgId: orgId
      },
      { isAddUid: true }
    )
    console.log('下载:', data)
    if (!data) {
      message.error('当前不存在可下载的附件')
    } else {
      const fileName = extractValueBetweenPercentAndPdf(data)
      console.log('文件名:', fileName)

      waitLoading(fetchDownload(data, fileName), {
        loadingText: '附件下载中...请稍后',
        errorText: '文件下载失败',
        successText: '文件下载成功'
      })
    }
  }
  // 保存评价
  const saveScore = async (): Promise<void> => {
    formRef.value
      .validate()
      .then(async () => {
        try {
          const { data } = await learningTasksManageApi.saveEvaluation(
            {
              learnTaskId: id,
              permissionUserId: currentStudentId.value,
              score: formState.scoreVal,
              permissionOrgId: orgId
            },
            { isAddUid: true }
          )
          console.log('保存评价：', data)
          message.success('评价分数已保存')
        } catch (error) {}
      })
      .catch((err: any) => {
        console.log(err)
      })
  }

  onMounted(() => {
    getStudentsList()
  })
</script>
<style lang="less" scoped>
  .download-attachment {
    img {
      vertical-align: text-bottom;
      margin-right: 6px;
    }
  }

  .main-wrap {
    height: 705px;

    .result-wrap {
      padding: 16px 20px 16px 16px;
      margin-right: 20px;
      width: 276px;
      // height: 100%;
      background: @background2;
      border-radius: 4px;

      .students-list {
        border-top: 1px solid @mask1;
        overflow-y: auto;
        padding: 20px 0;
        height: calc(100% - 116px);

        .student-item {
          justify-content: space-between;
          padding: 6px 12px;
          cursor: pointer;
          height: 40px;
          color: rgba(21, 23, 27, 0.95);
          line-height: 26px;

          .info {
            overflow: hidden;
            width: 170px;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }

        .bg {
          background-color: @mask1;
          border-radius: 8px;
        }
      }
    }

    .border {
      display: flex;
      width: calc(100% - 20px - 276px);
      border: 1px solid #e8e9eb;
      border-radius: 4px;

      .showing-wrap {
        overflow: auto;
        width: 100%;
        height: 705px;
        flex: 1;
        border-right: 1px solid #e8e9eb;

        .spin-wrap {
          height: 100%;

          .ant-spin {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 705px;
            max-height: 705px !important;
          }
        }
      }

      .save-wrap {
        padding: 16px 20px;
        width: 320px;
        // height: 705px;
        flex-direction: column;

        .form-item {
          margin-bottom: 20px;

          .title {
            padding: 0 16px;
            margin-bottom: 12px;
            width: 100%;
            height: 32px;
            color: rgba(16, 16, 20, 0.95);
            background: #fafafa;
            line-height: 32px;
            font-weight: 700;
          }

          .file {
            justify-content: space-between;
            align-items: center;
            padding: 16px;
            width: 100%;
            height: 74px;
            color: @text01;
            border: 1px solid @border2;
            border-radius: 6px;

            .info {
              align-items: center;

              img {
                margin-right: 6px;
              }

              .name {
                color: @text01;
                line-height: 22px;
              }

              .size {
                font-size: 12px;
                color: @text03;
                line-height: 20px;
              }
            }
          }
        }
      }
    }
  }
</style>
